<template>
  <div>
    <a-alert message="检测同半天内跨校区上课的教师" type="info" show-icon style="margin-bottom: 20px" />
    
    <a-form layout="inline" :form="form" @submit="handleSubmit" style="margin-bottom: 20px">
      <a-form-item label="检测日期范围">
        <a-range-picker
          v-decorator="['dateRange', { rules: [{ required: true, message: '请选择日期范围' }] }]"
          style="width: 240px"
          :disabledDate="disabledDate"
        />
      </a-form-item>
      
      <a-form-item label="校区设置">
        <a-select
          v-decorator="['campuses', { 
            initialValue: ['东校区', '西校区'],
            rules: [{ 
              validator: (_, value, callback) => {
                if (!value || value.length < 2) {
                  callback('请至少选择两个校区');
                } else {
                  callback();
                }
              }
            }]
          }]"
          mode="multiple"
          style="width: 200px"
          placeholder="请选择校区"
        >
          <a-select-option v-for="campus in campusOptions" :key="campus">
            {{ campus }}
          </a-select-option>
        </a-select>
      </a-form-item>
      
      <a-form-item>
        <a-button type="primary" html-type="submit" :loading="loading">
          开始检测
        </a-button>
        <!-- <a-button 
          style="margin-left: 8px" 
          :disabled="!data.length"
          @click="handleExport"
          :loading="exportLoading"
        >
          导出Excel
        </a-button> -->
      </a-form-item>
    </a-form>
    
    <a-table 
      :columns="columns" 
      :dataSource="paginatedData" 
      :loading="loading"
      :pagination="pagination"
      :scroll="{ x: 1000 }"
      size="middle"
      @change="handleTableChange"
    >
      <template slot="campus" slot-scope="text, record">
        <a-tag v-for="campus in record.campuses" :key="campus" color="red">
          {{ campus }}
        </a-tag>
      </template>
      
      <template slot="action" slot-scope="text, record">
        <a-button type="link" size="small" @click="showTeacherSchedule(record)">
          查看课表
        </a-button>
      </template>
    </a-table>
    
    <!-- 教师课表详情弹窗 -->
    <a-modal
      title="教师课表详情"
      :visible="scheduleVisible"
      @ok="handleScheduleOk"
      @cancel="handleScheduleCancel"
      width="1000px"
      :footer="null"
    >
      <a-descriptions bordered :column="2">
        <a-descriptions-item label="教师姓名">{{ currentTeacher.teacher }}</a-descriptions-item>
        <a-descriptions-item label="所属院系">{{ currentTeacher.department }}</a-descriptions-item>
        <a-descriptions-item label="跨校区天数">{{ currentTeacher.crossDays }}</a-descriptions-item>
        <a-descriptions-item label="总课程数">{{ currentTeacher.totalCourses }}</a-descriptions-item>
      </a-descriptions>
      
      <div style="margin-top: 20px">
        <h4>课程安排详情</h4>
        <a-table 
          :columns="scheduleColumns" 
          :dataSource="currentTeacher.scheduleDetails" 
          size="small"
          :pagination="{ pageSize: 5 }"
        />
      </div>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
// import { exportToExcel } from '@/utils/exportUtil'

const columns = [
  {
    title: '教师姓名',
    dataIndex: 'teacher',
    key: 'teacher',
    width: 120,
    fixed: 'left'
  },
  {
    title: '所属院系',
    dataIndex: 'department',
    key: 'department',
    width: 150
  },
  {
    title: '跨校区情况',
    dataIndex: 'campuses',
    key: 'campuses',
    scopedSlots: { customRender: 'campus' },
    width: 200
  },
  {
    title: '跨校区天数',
    dataIndex: 'crossDays',
    key: 'crossDays',
    sorter: (a, b) => a.crossDays - b.crossDays,
    width: 120
  },
  {
    title: '日期范围',
    dataIndex: 'dateRange',
    key: 'dateRange',
    width: 200
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    width: 100,
    fixed: 'right'
  }
]

const scheduleColumns = [
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
    width: 120
  },
  {
    title: '时间段',
    dataIndex: 'time',
    key: 'time',
    width: 100
  },
  {
    title: '校区',
    dataIndex: 'campus',
    key: 'campus',
    width: 120
  },
  {
    title: '教学楼',
    dataIndex: 'building',
    key: 'building',
    width: 120
  },
  {
    title: '教室',
    dataIndex: 'classroom',
    key: 'classroom',
    width: 120
  },
  {
    title: '课程名称',
    dataIndex: 'courseName',
    key: 'courseName'
  },
  {
    title: '班级',
    dataIndex: 'className',
    key: 'className',
    width: 120
  }
]

export default {
  beforeCreate() {
    this.form = this.$form.createForm(this)
  },
  
  data() {
    return {
      columns,
      scheduleColumns,
      loading: false,
      exportLoading: false,
      data: [],
      paginatedData: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: total => `共 ${total} 条`
      },
      campusOptions: ['东校区', '西校区', '南校区', '北校区', '中心校区'],
      scheduleVisible: false,
      currentTeacher: {
        teacher: '',
        department: '',
        crossDays: 0,
        totalCourses: 0,
        scheduleDetails: []
      }
    }
  },
  
  computed: {
    exportColumns() {
      return [
        { title: '教师姓名', dataIndex: 'teacher' },
        { title: '所属院系', dataIndex: 'department' },
        { 
          title: '跨校区情况', 
          dataIndex: 'campuses',
          render: campuses => campuses.join('、')
        },
        { title: '跨校区天数', dataIndex: 'crossDays' },
        { title: '日期范围', dataIndex: 'dateRange' }
      ]
    }
  },
  
  methods: {
    disabledDate(current) {
      // 禁用今天之后的日期
      return current && current > moment().endOf('day')
    },
    
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true
          // 模拟API调用
          setTimeout(() => {
            this.data = this.generateMockData(values)
            this.pagination.total = this.data.length
            this.pagination.current = 1
            this.updatePaginatedData()
            this.loading = false
            this.$message.success(`检测完成，共发现 ${this.data.length} 位教师存在跨校区上课情况`)
          }, 800)
        }
      })
    },
    
    generateMockData(params) {
      const [startDate, endDate] = params.dateRange
      const days = endDate.diff(startDate, 'days') + 1
      
      // 模拟数据生成
      const mockTeachers = [
        { id: 1, name: '李娜', department: '建筑工程系' },
        { id: 2, name: '阿依古丽·买买提', department: '信息工程系' },
        { id: 3, name: '王雪', department: '信息工程系' },
        { id: 4, name: '李廷', department: '机电工程系' },
        { id: 5, name: '张伟', department: '信息工程系' },
        { id: 6, name: '陈强', department: '机电工程系' },
        
      ]
      
      return mockTeachers.map(teacher => {
        const crossDays = Math.floor(Math.random() * 3) + 1
        const campuses = this.getRandomCampuses(params.campuses)
        
        // 生成详细的课程安排
        const scheduleDetails = []
        for (let i = 0; i < crossDays; i++) {
          const date = moment(startDate).add(Math.floor(Math.random() * days), 'days')
          scheduleDetails.push({
            date: date.format('YYYY-MM-DD'),
            time: '上午',
            campus: campuses[0],
            building: this.getRandomBuilding(campuses[0]),
            classroom: this.getRandomClassroom(),
            courseName: this.getRandomCourse(),
            className: this.getRandomClass()
          })
          scheduleDetails.push({
            date: date.format('YYYY-MM-DD'),
            time: '下午',
            campus: campuses[1],
            building: this.getRandomBuilding(campuses[1]),
            classroom: this.getRandomClassroom(),
            courseName: this.getRandomCourse(),
            className: this.getRandomClass()
          })
        }
        
        return {
          key: teacher.id,
          teacher: teacher.name,
          department: teacher.department,
          campuses: campuses,
          crossDays: crossDays,
          dateRange: `${startDate.format('YYYY-MM-DD')} 至 ${endDate.format('YYYY-MM-DD')}`,
          totalCourses: crossDays * 2,
          scheduleDetails: scheduleDetails
        }
      })
    },
    
    getRandomCampuses(availableCampuses) {
      if (availableCampuses.length < 2) return [availableCampuses[0]]
      const shuffled = [...availableCampuses].sort(() => 0.5 - Math.random())
      return shuffled.slice(0, 2)
    },
    
    getRandomBuilding(campus) {
      const buildings = {
        '东校区': ['东A楼', '东B楼', '东C楼'],
        '西校区': ['西1楼', '西2楼', '西3楼'],
        '南校区': ['南主楼', '南配楼'],
        '北校区': ['北教学楼', '北实验楼'],
        '中心校区': ['中心主楼', '中心东楼', '中心西楼']
      }
      return buildings[campus][Math.floor(Math.random() * buildings[campus].length)]
    },
    
    getRandomClassroom() {
      return `${Math.floor(Math.random() * 5) + 1}${Math.floor(Math.random() * 3) + 1}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}`
    },
    
    getRandomCourse() {
      const courses = ['数据结构', '操作系统', '计算机网络', '数据库原理', '编译原理', 'PLC与工业控制技术', '高等数学', '线性代数',  '有机化学']
      return courses[Math.floor(Math.random() * courses.length)]
    },
    
    getRandomClass() {
      const departments = ['计算机', '数学', '物理', '化学', '中文', '历史', '哲学', '经济', '管理']
      return `${departments[Math.floor(Math.random() * departments.length)]}20${Math.floor(Math.random() * 3)}${Math.floor(Math.random() * 2) + 1}`
    },
    
    handleTableChange(pagination) {
      this.pagination = pagination
      this.updatePaginatedData()
    },
    
    updatePaginatedData() {
      const { current, pageSize } = this.pagination
      const start = (current - 1) * pageSize
      const end = start + pageSize
      this.paginatedData = this.data.slice(start, end)
    },
    
    showTeacherSchedule(record) {
      this.currentTeacher = {
        teacher: record.teacher,
        department: record.department,
        crossDays: record.crossDays,
        totalCourses: record.totalCourses,
        scheduleDetails: record.scheduleDetails
      }
      this.scheduleVisible = true
    },
    
    handleScheduleOk() {
      this.scheduleVisible = false
    },
    
    handleScheduleCancel() {
      this.scheduleVisible = false
    },
    
    async handleExport() {
      // try {
      //   await exportToExcel({
      //     data: this.data,
      //     columns: this.exportColumns,
      //     filename: '跨校区教师检测结果',
      //     sheetName: '检测结果'
      //   })
      //   this.$message.success('导出成功')
      // } catch (error) {
      //   this.$message.error('导出失败: ' + error.message)
      // } finally {
      //   this.exportLoading = false
      // }
    }
  }
}
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 16px;
}

.ant-tag {
  margin-bottom: 4px;
}
</style>